<template>
  <div class="delivery-append-page">
    <top class="top" :key="id + '-top'"></top>
    <middle ref="data" class="middle" :key="id + '-middle'"></middle>
    <!--
      确认分为两个步骤
      第一步点击确认，跳出这份送货单的相关信息，
      第二步确认这些信息，正式新增送货单
     -->
    <bottom
      class="bottom"
      @appendDelivery="appendDelivery"
      @confirm="confirm"
      @handleCancel="handleCancel"
      :summary="summary"
    />
  </div>
</template>

<script>
import Top from './layout/append/Top';
import Middle from './layout/append/Middle';
import Bottom from './layout/append/Bottom';

import {
  deliveryAppendReq,
  deliveryAddOrderReq,
} from '@/requests/deliveryRequests';

export default {
  name: 'DeliveryAppend',
  data() {
    return {
      id: this.$route.params.clientId,
      summary: {
        clientId: 0,
        name: 0,
        totalAmount: 0,
        orderQuantity: 0,
      },
    };
  },
  computed: {},
  mounted() {
    this.load();
  },
  watch: {
    $route(to, from) {
      if (to.params.id !== this.id && to.name == 'DeliveryAppend') {
        this.load();
      }
    },
  },
  methods: {
    /**
     * 点击页面上的确定按钮，此时还没有开始请求后端，只是提供总结的信息
     */
    appendDelivery() {
      const form = this.$refs.data.getFormData().form;
      const totalAmount = this.$refs.data.getTableData().totalAmount;
      const orderQuantity = this.$refs.data.getTableData().orderQuantity;
      this.summary = {
        clientId: form.clientId,
        name: form.name,
        totalAmount: totalAmount,
        orderQuantity: orderQuantity,
      };
    },
    confirm() {
      const delivery = Object.assign({}, this.$refs.data.getFormData().form);
      const totalAmount = this.$refs.data.getTableData().totalAmount;
      const orderQuantity = this.$refs.data.getTableData().orderQuantity;
      const orderIds = this.$refs.data.getTableData().selectedRowKeys;

      delivery.totalAmount = totalAmount;
      delivery.orderQuantity = orderQuantity;
      delivery.deliveryDate = delivery.deliveryDate.split('-').join('');
      delete delivery.name;
      delete delivery.clientId;

      if (this.$route.query.deliveryNumber) {
        this.deliveryAddOrder(orderIds);
        return;
      }

      const loaded = this.$message.loading(
        '正在添加送货单，请勿重复点击提交',
        0
      );
      deliveryAppendReq(this.id, delivery, orderIds)
        .then((res) => {
          loaded();
          // 如果成功，应当得到一张送货单的Id
          let deliveryId = res.data.id;

          // 新增成功，更新页面
          this.id = `${this.id}-trash`;
          this.$router.push({
            name: 'DeliveryCheck',
            params: {
              id: deliveryId,
            },
          });
          this.$notification['success']({
            message: '新增送货单',
            description: `新增送货单成功，生成送货单号 ${deliveryId}`,
          });

          // 更新送货单和订单缓存
          this.$store.commit('updateDeliveriesCache');
          this.$store.commit('updateOrdersCache');
        })
        .catch((err) => {
          loaded();
          this.$notification['error']({
            message: '新增送货单',
            description: `新增送货单失败，失败信息 ${err.response.data.message}`,
          });
        });

      // // 通知后端新增送货单
    },
    deliveryAddOrder(orderIds) {
      const deliveryNumber = this.$route.query.deliveryNumber;
      const deliveryId = this.$route.query.deliveryId;
      // 为送货单添加订单
      const loaded = this.$message.loading(
        '正在为送货单添加订单，请勿重复点击提交',
        0
      );
      deliveryAddOrderReq(deliveryId, orderIds)
        .then((res) => {
          loaded();
          // 如果成功，应当得到一张送货单
          let deliveryId = res.data.id;

          // 新增成功，更新页面
          this.id = `${this.id}-trash`;
          this.$router.push({
            name: 'DeliveryCheck',
            params: {
              id: deliveryId,
            },
          });
          this.$notification['success']({
            message: '新增送货单',
            description: `为送货单添加订单成功，送货单号 ${deliveryId}`,
          });

          // 更新送货单和订单缓存
          this.$store.commit('updateDeliveriesCache');
          this.$store.commit('updateOrdersCache');
        })
        .catch((err) => {
          err = err.response?.data.message ?? err.data.message ?? err;
          loaded();
          this.$notification['error']({
            message: '新增送货单',
            description: `为送货单添加订单失败，失败信息 ${err}`,
          });
        });
    },
    // 送货单不应保存信息
    load() {
      this.id = this.$route.params.clientId;
    },
    handleCancel() {
      this.id = `${this.id}-cancel`;
    },
  },
  components: {
    Top,
    Middle,
    Bottom,
  },
};
</script>

<style scoped lang="scss">
.delivery-append-page {
  > .top {
    margin-top: 2vh;
    margin-bottom: 1vh;
    padding-left: 20px;
  }
  > .middle {
    margin: 0 30px;
  }
  > .bottom {
    display: flex;
    padding-right: 100px;
    justify-content: flex-end;
  }
}
</style>
